package com.alstudio.ui.module.main.fragment.discovery;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.module.xmpp.request.ALUiXmppRequestType;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.pojo.module.user.User;
import com.alstudio.ui.module.main.MainActivity.DiscoveryRefreshType;
import com.alstudio.ui.module.main.SearchUserActivity;
import com.alstudio.ui.module.main.fragment.FragmentUpdateDataEngine;
import com.alstudio.ui.module.user.UserHomePageAcitivty;
import com.alstudio.utils.absListView.loadmore.AbsListViewLoadMoreManager;
import com.alstudio.utils.absListView.loadmore.OnLoadMoreListener;
import com.alstudio.utils.formater.age.ALAgeFormatter;
import com.alstudio.utils.formater.sex.ALSexFormatter;
import com.alstudio.utils.formater.time.ALTimeUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.view.ViewUtils;
import com.alstudio.view.absadapter.BaseUserListAdapter;
import com.alstudio.view.toast.MyToastUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.extras.SoundPullEventListener;
import com.loovee.imaohu.R;

public class DiscoveryFragment extends Fragment implements
		FragmentUpdateDataEngine {

	private PullToRefreshListView mPullRefreshListView;
	private PullToRefreshListView mPullRefreshGridView;
	private ListView mListView;
	private ListView mGridView;
	private DiscoveryGridItemAdapter gridViewAdapter;

	public enum ShowType {
		TYPE_LISTVIEW, TYPE_GRIDVIEW;
	}

	private ShowType mShowType = ShowType.TYPE_GRIDVIEW;
	// 加载更多
	private boolean isLoadingMoreData = false;
	// 是否正在重新刷新数据
	private boolean isRefreshing = false;

	// 发现，起始请求
	private int discoveryStartIndex = ALLocalEnv.LOAD_MORE_START_INDEX;;
	// 发现，结束请求
	private int discoveryEndIndex = ALLocalEnv.LOAD_MORE_END_INDEX;

	// To know if the list is loading more items
	private boolean mIsLoadingMore = false;

	private final String REFRESH_ALL = "";
	private final String REFRESH_FEMALE = "female";
	private final String REFRESH_MALE = "male";

	private String refreshType = REFRESH_ALL;

	private boolean isInited = false;

	// 超时20S
	private final int REQUEST_TIME_OUT = 20 * 1000;

	// 超时处理
	private Handler mHandler = new Handler();

	private void startTimer() {
		stopTimer();
		ALLog.d("开启计时器");
		mHandler.postDelayed(requestTimeoutTask, REQUEST_TIME_OUT);
	}

	private void stopTimer() {
		mHandler.removeCallbacks(requestTimeoutTask);
	}

	private Runnable requestTimeoutTask = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			onLoadComplete();
			MyToastUtil.getInstance().showCenterToastOnCenter(
					R.string.TxtLoadFail);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ALLog.d("onCreate");
	}

	private BaseUserListAdapter adapter;
	private View headerView;
	private View headerViewForGrid;
	private ArrayList<User> dataList;
	private AbsListViewLoadMoreManager loadMoreManagerForList;
	private AbsListViewLoadMoreManager loadMoreManagerForGrid;
	private OnLoadMoreListener loadMoreListener = new OnLoadMoreListener() {

		@Override
		public void onLoadMore() {
			// TODO Auto-generated method stub
			ALLog.d("加载更多");
			if (!ALLocalEnv.isSendXmppDataEnable()) {
				onLoadComplete();
				return;
			}
			startTimer();
			isLoadingMoreData = true;
			requestDiscoveryUsersList(true, true);
		}
	};

	/**
	 * 
	 */
	public DiscoveryFragment() {
		// TODO Auto-generated constructor stub
		this.dataList = new ArrayList<User>();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		ALLog.d("onCreateView");

		final View v = inflater.inflate(R.layout.main_discovery_list,
				container, false);
		headerView = inflater.inflate(R.layout.discovery_search_header_view,
				null);
		headerView.setOnClickListener(headerViewClickListener);

		headerViewForGrid = inflater.inflate(
				R.layout.discovery_search_header_for_grid, null);
		headerViewForGrid.setOnClickListener(headerViewClickListener);
		initPullListView(v);

		initPullGridView(v);

		addSoundListener();
		showData();
		isInited = true;

		// new Handler().postDelayed(new Runnable() {
		//
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// invokeChangeToTabHome("onCreateView");
		// }
		// }, 1000);
		requestDiscoveryUsersList(false, false);
		return v;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ALLog.d("onResume");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onHiddenChanged(boolean)
	 */
	@Override
	public void onHiddenChanged(boolean hidden) {
		// TODO Auto-generated method stub
		super.onHiddenChanged(hidden);
		ALLog.d("onHiddenChanged");

		if (!hidden) {
			ALLog.d("onHiddenChanged 开始请求数据");
			invokeChangeToTabHome("onHiddenChanged 开始请求数据");
		}
	}

	public boolean isInited() {
		return isInited;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onAttach(android.app.Activity)
	 */
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		ALLog.d("onAttach");
	}

	public void invokeChangeToTabHome(String calling) {
		ALLog.d("calling time " + calling);
		if (dataList.size() == 0 && isInited && !isRefreshing) {
			ALLog.d("发现没有数据，开始请求");
			requestDiscoveryUsersList(true, false);
		}
	}

	private void requestDiscoveryUsersList(boolean manual, boolean loadMore) {
		if (ALLocalEnv.isSendXmppDataEnable()) {
			if (!loadMore) {
				discoveryStartIndex = ALLocalEnv.LOAD_MORE_START_INDEX;
				discoveryEndIndex = ALLocalEnv.LOAD_MORE_END_INDEX;
				if (manual) {
					onRefreshReq();
					return;
				}
			} else {
				discoveryStartIndex = dataList.size();
				discoveryEndIndex = discoveryStartIndex
						+ ALLocalEnv.LOAD_MORE_COUNT_PER_TIME;
				ALLog.d("更新发现请求起止点  " + discoveryStartIndex + " "
						+ discoveryEndIndex);
			}
			ALUiXmppRequestCreator.postALUiXmppLoadMoreEvent(
					ALUiXmppRequestType.XMPP_DISCOVERY_REQUEST,
					discoveryStartIndex + "", discoveryEndIndex + "",
					refreshType);
		} else {
			onDataUpdateReq(false, null, false);
		}

	}

	/**
	 * 初始化列表形式的发现下来刷新控件
	 * 
	 * @param parent
	 */
	private void initPullListView(View parent) {

		mPullRefreshListView = (PullToRefreshListView) parent
				.findViewById(R.id.pull_refresh_list);

		// mPullRefreshListView.setScrollingWhileRefreshingEnabled(false);
		// mPullRefreshListView.setMode(Mode.DISABLED);

		mListView = mPullRefreshListView.getRefreshableView();
		loadMoreManagerForList = new AbsListViewLoadMoreManager(mListView,
				ALLocalEnv.getLocalEnv());
		loadMoreManagerForList.setOnLoadMoreListener(loadMoreListener);
		mListView.addHeaderView(headerView);
		mListView.setSelector(R.drawable.list_default_selector);

		adapter = new BaseUserListAdapter(dataList);
		adapter.setLayoutRes(R.layout.main_discovery_single_item2);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long id) {
				// TODO Auto-generated method stub
				if (id == -1) {
					// 点击的是headerView或者footerView
					return;
				}
				int realPosition = (int) id;
				User u = (User) adapter.getItem(realPosition);
				Intent intent = new Intent(getActivity(),
						UserHomePageAcitivty.class);
				intent.putExtra("user", u);
				getActivity().startActivity(intent);
			}
		});
		mPullRefreshListView.setOnRefreshListener(pullRefreshListener);

	}

	/**
	 * 初始化grid形式的发现下拉刷新控件
	 * 
	 * @param parent
	 */
	private void initPullGridView(View parent) {
		mPullRefreshGridView = (PullToRefreshListView) parent
				.findViewById(R.id.pull_refresh_grid_list);
		// mPullRefreshGridView.setMode(Mode.DISABLED);
		// mPullRefreshGridView.setScrollingWhileRefreshingEnabled(false);

		mGridView = mPullRefreshGridView.getRefreshableView();
		loadMoreManagerForGrid = new AbsListViewLoadMoreManager(mGridView,
				ALLocalEnv.getLocalEnv());
		loadMoreManagerForGrid.setOnLoadMoreListener(loadMoreListener);

		mGridView.addHeaderView(headerViewForGrid);

		mGridView.setSelector(R.drawable.list_default_selector);

		gridViewAdapter = new DiscoveryGridItemAdapter(dataList);
		mGridView.setAdapter(gridViewAdapter);

		// Set a listener to be invoked when the list should be refreshed.
		mPullRefreshGridView.setOnRefreshListener(pullRefreshListener);

	}

	/**
	 * 下拉刷新监听器
	 */
	private OnRefreshListener<ListView> pullRefreshListener = new OnRefreshListener<ListView>() {

		@Override
		public void onRefresh(PullToRefreshBase<ListView> refreshView) {
			// TODO Auto-generated method stub

			if (!ALLocalEnv.isSendXmppDataEnable()) {
				onLoadComplete();
				return;
			}

			if (isRefreshing) {
				ALLog.d("卡住了");
				return;
			}
			startTimer();
			ALLog.d("开始请求");
			isRefreshing = true;
			String label = DateUtils.formatDateTime(ALLocalEnv.getLocalEnv(),
					System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
							| DateUtils.FORMAT_SHOW_DATE
							| DateUtils.FORMAT_ABBREV_ALL);

			// Update the LastUpdatedLabel
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			requestDiscoveryUsersList(false, false);
		}

	};

	private void addSoundListener() {
		/**
		 * Add Sound Event Listener
		 */
		SoundPullEventListener<ListView> soundListener = new SoundPullEventListener<ListView>(
				getActivity());
		soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
		soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
		soundListener.addSoundEvent(State.REFRESHING, R.raw.refreshing_sound);
		mPullRefreshListView.setOnPullEventListener(soundListener);
		mPullRefreshGridView.setOnPullEventListener(soundListener);
	}

	/**
	 * 搜索段点击事件
	 */
	private OnClickListener headerViewClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(getActivity(), SearchUserActivity.class);
			startActivity(intent);
		}
	};

	/**
	 * 
	 * @param gridview
	 */
	public void setShowType(ShowType type) {
		mShowType = type;
		showData();
	}

	/**
	 * 
	 * @param gridview
	 */
	public void setShowType(boolean isList) {
		if (isList) {
			mShowType = ShowType.TYPE_LISTVIEW;
		} else {
			mShowType = ShowType.TYPE_GRIDVIEW;

		}
		showData();
	}

	public boolean isShowingList() {
		return mShowType == ShowType.TYPE_LISTVIEW ? true : false;
	}

	/**
	 * 显示数据
	 */
	private void showData() {
		switch (mShowType) {
		case TYPE_GRIDVIEW:
			ViewUtils.showView(mPullRefreshGridView);
			ViewUtils.goneView(mPullRefreshListView);
			break;
		case TYPE_LISTVIEW:
			ViewUtils.showView(mPullRefreshListView);
			ViewUtils.goneView(mPullRefreshGridView);
			break;
		}
	}

	public void setDisplayData(ArrayList<User> data) {
		this.dataList = data;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.module.main.fragment.FragmentUpdateDataEngine#onDataUpdateReq
	 * (boolean)
	 */
	@Override
	public void onDataUpdateReq(boolean success, Object data, boolean hasMore) {
		// TODO Auto-generated method stub
		// 停止界面刷新

		onLoadComplete();

		mIsLoadingMore = false;

		if (success) {
			// 刷新成功，更新列表
			ALLog.d("刷新成功，更新列表");
			@SuppressWarnings("unchecked")
			ArrayList<User> tmps = (ArrayList<User>) data;
			if (tmps.size() > 0) {
				if (isRefreshing) {
					dataList.clear();
					isRefreshing = false;
				}
				dataList.addAll(tmps);

				tmps.clear();
				tmps = null;
			}
			if (!hasMore) {
				loadMoreManagerForList.setOnLoadMoreListener(null);
				loadMoreManagerForGrid.setOnLoadMoreListener(null);
			} else {
				loadMoreManagerForList.setOnLoadMoreListener(loadMoreListener);
				loadMoreManagerForGrid.setOnLoadMoreListener(loadMoreListener);
			}
			loadMoreManagerForGrid.onLoadMoreComplete();
			loadMoreManagerForList.onLoadMoreComplete();
			adapter.notifyDataSetChanged();
			gridViewAdapter.notifyDataSetChanged();

		}
		isRefreshing = false;

	}

	private void onLoadComplete() {
		isRefreshing = false;
		mPullRefreshListView.onRefreshComplete();
		mPullRefreshGridView.onRefreshComplete();
		loadMoreManagerForList.onLoadMoreComplete();
		loadMoreManagerForGrid.onLoadMoreComplete();
		stopTimer();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.module.main.fragment.FragmentUpdateDataEngine#onRefreshReq
	 * ()
	 */
	@Override
	public void onRefreshReq() {
		// TODO Auto-generated method stub
		if (ALLocalEnv.isSendXmppDataEnable()) {
			requestDiscoveryUsersList(false, false);
//			mPullRefreshListView.setRefreshing();
//			mPullRefreshGridView.setRefreshing();
		}
	}

	/**
	 * 重新刷新类型
	 * 
	 * @param type
	 */
	public void setRefreshType(DiscoveryRefreshType type) {
		switch (type) {
		case TYPE_ALL:
			refreshType = REFRESH_ALL;
			break;
		case TYPE_FEMALE:
			refreshType = REFRESH_FEMALE;
			break;
		case TYPE_MALE:
			refreshType = REFRESH_MALE;
			break;
		}
		requestDiscoveryUsersList(true, false);
	}

	class ItemAdapter extends BaseAdapter {

		private ArrayList<User> data = new ArrayList<User>();

		/**
		 * 
		 */
		public ItemAdapter(ArrayList<User> data) {
			// TODO Auto-generated constructor stub
			this.data = data;
		}

		private class ViewHolder {
			public TextView nick_name, time, location_age;
			public ImageView image, sex, vauth;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			final ViewHolder holder;
			if (convertView == null) {
				view = getActivity().getLayoutInflater().inflate(
						R.layout.main_discovery_single_item, parent, false);
				holder = new ViewHolder();
				holder.time = (TextView) view.findViewById(R.id.time);
				holder.nick_name = (TextView) view.findViewById(R.id.nick_name);
				holder.location_age = (TextView) view
						.findViewById(R.id.location_age);
				holder.sex = (ImageView) view.findViewById(R.id.sex);
				holder.vauth = (ImageView) view.findViewById(R.id.vauth);

				holder.image = (ImageView) view.findViewById(R.id.icon);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}

			setupViewItem(holder, position);

			return view;
		}

		private void setupViewItem(ViewHolder holder, int pos) {
			User u = data.get(pos);
			holder.nick_name.setText(u.getNick());
			holder.time.setText(ALTimeUtils.formatTime(u
					.getLastLoginTimeStamp()));

			holder.location_age.setText(ALAgeFormatter.getAgeLocation(
					u.getBirtyday(), u.getLocation()));

			holder.sex.setImageResource(ALSexFormatter.transSexDrawable(u
					.getSex()));
			if (u.isVauthed()) {
				holder.vauth.setImageResource(R.drawable.find_user_icon_vip);
			} else {
				holder.vauth.setImageBitmap(null);
			}

			ALLocalEnv.getLocalEnv().displayImagePluginServerlet(
					u.getImageFileId(), holder.image,
					ALLocalEnv.getLocalEnv().getNormalRectImageDisplayOption());
			// ALLocalEnv
			// .getLocalEnv()
			// .getImageLoader()
			// .displayImage(
			// u.getImageFileId(),
			// holder.image,
			// ALLocalEnv.getLocalEnv()
			// .getNormalRectImageDisplayOption());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.module.main.fragment.FragmentUpdateDataEngine#onDatUpdateReq
	 * (com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppData)
	 */
	@Override
	public void onDataUpdateReq(ALXmppEvent data) {
		// TODO Auto-generated method stub

	}

	public boolean isDataEmpty() {
		// TODO Auto-generated method stub
		if (dataList != null && dataList.size() == 0) {
			return true;
		}
		return false;
	}

}
